<template>
	<view class="content">
		<z-paging ref="paging" v-model="talkList" use-chat-record-mode safe-area-inset-bottom @query="initMsg">
			
			<view v-for="(item,index) in talkList" :key="index" style="position: relative;">
				<!-- style="transform: scaleY(-1)"必须写，否则会导致列表倒置 -->
				<view style="transform: scaleY(-1);">
					<chat-item :item="item"></chat-item>
				</view>
			</view>
			
			<!-- 底部聊天输入框 -->
			<template #bottom>
				<chat-input-bar ref="inputBar" @send="send" />
			</template>
		</z-paging>
		
	</view>
</template>

<script>
	import {
		parseTime
	} from "@/utils/date.js"
	
	export default {
		data() {
			return {
				appId : "z1DeJAFyakkIVAg5BRMbm2aQXh8yUywM", 
				secretKey : "IkTEaD48DFLhdV9iMIWQpzJphTln8hiC",
				initAiInfo : [{ //初始化的ai消息
					time: parseTime(Date.now()),
					icon: '/static/icon/hn.png',
					name: '海纳AI',
					content: '海纳AI为您服务：\n可以问我有关学校规章制度的所有问题哦\n越完整的描述，我越精确!', // 消息内容
					isMe: false,
					end:true
				}], 
				talkList: [], 
				msg: '', // 用户发送的消息
				currentMassage:{}, //接收的单条消息
				currentContent:'', //需要打印的内容
				currentIndex:0, //当前打印文字的下标
				isTyping:false, //打印标识
				sendState:false, //是否发送完毕
			}
		},
		methods: {
			initMsg() {
				this.$refs.paging.complete(this.initAiInfo);
			},
			//用户发送消息
			send(msg){
				this.msg = msg;
				if(this.sendState){
					return false;
				}
				if (!this.msg) {
					return false;
				}
				uni.showLoading({
					title: '回答中...'
				})
				this.$refs.inputBar.setMsg('');
				this.sendState = true;
				this.talkList.unshift({
					time: parseTime(Date.now()),
					icon: '/static/icon/avatar.png',
					name: '我',
					content: this.msg, 
					isMe: true,
					end:true
				})
				this.talkList.unshift({
					icon:'/static/icon/hn.png',
					name: '海纳AI',
					content: '', 
					isMe: false,
					end:false,
				})
				this.$forceUpdate()
				this.toSend();
			},
			// 发送信息
			toSend() {
				var that = this;
				
				//调用ai接口，获取结果
				const requestTask = this.getResultByAi(this.msg);
				
				requestTask.onHeadersReceived(function(resp) {
					if(!resp.header.hasOwnProperty("Transfer-Encoding")) {
						uni.hideLoading();
						that.talkList[0].content = '哎呀呀,我的脑袋突然短路了,请重新问我试试吧!';
						that.talkList[0].end = true;
						that.currentIndex = 0;
						that.currentContent = '';
						that.sendState = false;
					}
				});
				
				requestTask.onChunkReceived(function(response) {
					//流转字符串
					const uint8Array = new Uint8Array(response.data);
					let text = String.fromCharCode.apply(null, uint8Array);
					text = decodeURIComponent(escape(text));
					
					// 查找 data: 所在的行
					let dataLine = text.split('\n').find(line => line.startsWith('data:'));
					if(dataLine) {
						// 查找 data: 的位置
						let dataIndex = dataLine.indexOf('data:');
						 
						// 如果找到了 data:，则提取其后面的内容
						if (dataIndex !== -1) {
						    // dataIndex + 'data:'.length 是为了跳过 'data:' 本身和后面的冒号
						    let jsonString = dataLine.substring(dataIndex + 'data:'.length);
						    
						     let obj = JSON.parse(jsonString);
						     if(obj.status === 0 && obj.data !== null && obj.data.message !== null
								&& obj.data.message.content.length>0) {
								let res = obj.data.message.content[0];
								
								if(res.data !== null ) {
									uni.hideLoading();
									
									let end = obj.data.message.endTurn || res.isFinished;
									
									that.currentMassage = {
										is_end: end,
										result : res.data.text
									} 
									that.currentContent += that.currentMassage.result;
									that.startTyping();
								}
							 }
						} else {
						    console.log('没有找到 data:');
						}
					}
				 });
			},
			//开始打印
			startTyping() {
				if (this.isTyping) return;
				this.isTyping = true;
				
				setTimeout(() => {
					if (this.currentIndex <= this.currentContent.length) {
						this.talkList[0].content = this.currentContent.substring(0, this.currentIndex++);
						this.$forceUpdate()
						this.isTyping = false;
						this.startTyping();
					} else {
						if(this.currentMassage.is_end){
							this.talkList[0].end = true;
							this.currentIndex = 0;
							this.currentContent = '';
							this.sendState = false;
						}
						this.isTyping = false;
					}
				}, 50);
			},
			//调用文心智能体
			getResultByAi(msg) {
				var that = this;
				return uni.request({
					method:'post',
					header: {
					  'content-type': 'application/json',
					},
					url: `https://agentapi.baidu.com/assistant/conversation?appId=${this.appId}&secretKey=${this.secretKey}`,
					data: {
						"source": this.appId,
						"from": "openapi",
						"openId": uni.getStorageSync("phone"),
						"message": {
							"content": {
								"type": "text",
								"value": {
									"showText": msg
								}
							}
						},
					},
					enableChunked: true,
					complete: ()=> {},
					success(res) {
						if(res.statusCode !== 200) {
							uni.hideLoading();
							that.talkList[0].content = '哎呀呀,我的脑袋突然短路了,请重新问我试试吧!';
							that.talkList[0].end = true;
							that.currentIndex = 0;
							that.currentContent = '';
							that.sendState = false;
						}
					},
					fail: function (err) {
						uni.hideLoading();
						that.talkList[0].content = '哎呀呀,我的脑袋突然短路了,请重新问我试试吧!';
						that.talkList[0].end = true;
						that.currentIndex = 0;
						that.currentContent = '';
						that.sendState = false;
					}
				})
			}
		}
	}
</script>

<style scoped>
	.header{
		background-color: red;
		font-size: 20rpx;
		padding: 20rpx;
		color: white;
	}
	.popup {
		position: absolute;
		top: -20px;
		height: 200rpx;
		width: 400rpx;
		background-color: red;
		z-index: 1000;
	}
</style>
